import { defineStore } from 'pinia';
import { Session, Local } from '/@/utils/storage';
import loginapi from '/@/api/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			photo: '',
			itCode: '',
			tenantCode: '',
			remoteToken: '',
			currentTenant: '',
			time: 0,
			isDebug: false,
			menu: [],
			roles: [],
			authBtnList: [],
			groups: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos: any = await this.getApiUserInfo();
				if (userInfos) {
					Session.set('userInfo', userInfos);
					this.userInfos = userInfos;
				}
			}
		},
		async getApiUserInfo() {
			return loginapi().getUserInfo().then(async res => {
				const userInfos = {
					userName: res.Name,
					remoteToken: res.RemoteToken ?? '',
					itCode: res.ITCode,
					tenantCode: res.TenantCode ?? '',
					currentTenant: res.CurrentTenant ?? '',
					time: new Date().getTime(),
					photo: '',
					isDebug: true,
					roles: [],
					menu: [],
					authBtnList: [],
					groups: [],
				};
				if (res.PhotoId !== undefined) {
					userInfos.photo = `/api/_file/getfile/${res.PhotoId}?width=25&height=25`;
				}
				if (res.Roles !== undefined) {
					userInfos.roles = res.Roles;
				}
				if (res.Attributes?.Actions !== undefined) {
					userInfos.authBtnList = res.Attributes.Actions;
				}
				if (res.Attributes?.IsDebug !== undefined) {
					userInfos.isDebug = res.Attributes.IsDebug;
				}
				if (res.Attributes?.Menus !== undefined) {
					userInfos.menu = res.Attributes.Menus;
				}
				if (res.Groups !== undefined) {
					userInfos.groups = res.Groups;
				}
				return userInfos;
			}).catch(() => {
				Session.clear();
				Local.remove("token");
				window.location.href = '/';
			});
		},
		logout() {
			Session.clear();
			Local.remove('token');
			this.userInfos = {
				userName: '',
				photo: '',
				itCode: '',
				tenantCode: '',
				remoteToken: '',
				currentTenant: '',
				time: 0,
				isDebug: false,
				menu: [],
				roles: [],
				authBtnList: [],
				groups: [],
			};
		},
	},
});
